import subprocess
import json
import sys
import os
from datetime import datetime


def install_package(package_name):
    try:
        subprocess.check_call([sys.executable, "-m", "pip", "install", package_name])
        return True
    except subprocess.CalledProcessError as e:
        return False


def run_test(package_name):
    log = {
        "package": package_name,
        "install_success": install_package(package_name),
        "test_success": False,
        "log": "",
        "timestamp": datetime.utcnow().isoformat()
    }
    try:
        # TODO: 后续支持自定义测试用例
        __import__(package_name)
        log["test_success"] = True
    except Exception as e:
        log["log"] = str(e)

    os.makedirs("logs", exist_ok=True)
    with open(f"logs/{package_name}.json", "w") as f:
        json.dump(log, f, indent=2)


if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("Usage: python auto_test.py <package_name>")
        sys.exit(1)
    run_test(sys.argv[1])